
# 在任务处理者一端加这几句
import os
# import django
# os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dailyfresh.settings")
# django.setup()


from celery import Celery
from django.core.mail import send_mail
from django.conf import settings
from django.template import loader
import time
from goods.models import GoodsType, Goods, GoodsSKU, IndexGoodsBanner, IndexPromotionBanner, IndexTypeGoodsBanner

# 创建一个Celery类的实例对象
app = Celery('celery_tasks.tasks', broker='redis://127.0.0.1:6379/8')

# 定义任务函数
@app.task
def send_register_active_email(to_email, username, token):
    '''发送激活邮件'''
    # 组织邮件信息
    subject = '天天生鲜欢迎信息'
    message = ''
    sender = settings.EMAIL_FROM
    receiver = [to_email]
    html_message = '<h1>%s, 欢迎您成为天天生鲜注册会员</h1>请点击下面链接激活您的账户<br/><a href="http://127.0.0.1:8000/user/active/%s">http://127.0.0.1:8000/user/active/%s</a>' % (username, token, token)

    send_mail(subject, message, sender, receiver, html_message=html_message)

@app.task
def generate_static_index_html():
    indexGoodsBannner = IndexGoodsBanner.objects.filter(is_delete=False).order_by("index")
    indexPromotionBanner = IndexPromotionBanner.objects.filter(is_delete=False).order_by("index")
    goodsTypes = GoodsType.objects.filter(is_delete=False)

    for goodsType in goodsTypes:
        bannars = IndexTypeGoodsBanner.objects.filter(is_delete=False, type=goodsType, display_type=1).order_by("index")
        titles = IndexTypeGoodsBanner.objects.filter(is_delete=False, type=goodsType, display_type=0).order_by("index")
        goodsType.bannars = bannars
        goodsType.titles = titles

    param = {
        "indexGoodsBannner": indexGoodsBannner,
        "indexPromotionBanner": indexPromotionBanner,
        "goodsTypes": goodsTypes
    }

    temp = loader.get_template('static_index.html')
    static_index_html= temp.render(param)
    save_path = os.path.join(settings.BASE_DIR, 'static/index.html')
    with open(save_path, 'w') as f:
        f.write(static_index_html)